<template>
  <div>
    <div style="padding: 18px; border-bottom: solid 1px #EEE">
      <el-button type="primary" @click="handleCreate()">添加新的人员</el-button>
    </div>
    <el-table
      :data="userList"
      style="width: 100%"
      row-key="id"
      border
      lazy
    >
      <el-table-column
        prop="username"
        label="用户名称"
        header-align="center"
        align="left"
      />
      <el-table-column
        label="角色权限"
        header-align="center"
        align="left"
      >
        <template v-slot="{ row }">{{ showRoleName(row.roleId) }}</template>
      </el-table-column>
      <el-table-column
        label="状态"
        width="100"
        align="center"
      >
        <template v-slot="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status | statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
      >
        <template v-slot="{row}">
          <span>{{ row.createTime | timeFilter('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="300"
        align="center"
      >
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="handleAcc(row)"
          >
            设置帐号
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button v-if="row.status" type="danger" size="small" icon="el-icon-close" @click="confirmStatus(row)">停用</el-button>
          <el-button v-else type="success" size="small" icon="el-icon-check" @click="confirmStatus(row)">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹出框-人员管理 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="tempData" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="dialogStatus == 'update'" label="所属商家">
          <el-input v-model="sellerName" type="input" readonly />
        </el-form-item>
        <el-form-item v-else label="所属商家">
          <el-select v-model="tempData.sellerId" placeholder="请选择商家">
            <el-option
              v-for="item in sellerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="tempData.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="tempData.gender" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in genderOptions" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthDate">
          <el-date-picker v-model="tempData.birthDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="tempData.roleId" class="filter-item" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="tempData.mobile" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="tempData.status" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():confirmEdit(tempData)">提交</el-button>
      </div>
    </el-dialog>

    <!-- 弹出框-帐号管理 -->
    <el-dialog :title="accTitle[dialogStatus]" :visible.sync="accFormVisible">
      <el-form ref="accForm" :model="accData" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="所属商家">
          <span>{{ sellerName }}</span>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <span>{{ accData.name }}</span>
        </el-form-item>
        <el-form-item label="用户帐号" prop="userName">
          <el-input v-model="accData.userName" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="accData.status" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in accStatus" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="accData.userName" label="创建时间" prop="createTime">
          <span>{{ accData.createTime | timeFilter }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="accFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createAccData():confirmAccEdit(accData)">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getAdminList, editUserInfo, editUserStatus, addUserInfo, getAdmin, addAdmin, editAdmin } from '@/api/admin'
import { genderInfo, parseTime } from '@/utils'
import store from '@/store'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'gray',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    },
    statusName(status) {
      const statusMap = {
        0: '无效',
        1: '有效'
      }
      return statusMap[status]
    },
    timeFilter(time, format) {
      return parseTime(time, format)
    },
    genderFilter(gender) {
      return genderInfo(gender)
    }
  },
  data() {
    const validateUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户帐号'))
      } else {
        callback()
      }
    }
    return {
      userList: [],
      roleList: [],
      sellerList: [],
      textMap: {
        update: '修改',
        create: '新增'
      },
      accTitle: {
        update: '修改',
        create: '新增 - 该用户没有帐号，为该用创建帐号'
      },
      dialogStatus: 'create',
      dialogFormVisible: false,
      accFormVisible: false,
      sellerName: store.getters.orgName,
      tempData: {
        id: 0,
        userName: '',
        accountId: '',
        sellerId: 0,
        sellerName: '',
        roleId: 0,
        avatar: '',
        status: 1
      },
      accData: {
        userName: '',
        name: '',
        status: 1
      },
      statusOptions: [{ key: 0, value: '无效' }, { key: 1, value: '有效' }],
      accStatus: [{ key: 0, value: '无效' }, { key: 1, value: '有效' }, { key: 2, value: '锁定' }],
      genderOptions: [{ key: 1, value: '男' }, { key: 2, value: '女' }],
      rules: {
        userName: [
          { validator: validateUserName, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.sellerList = [{ id: store.getters.orgId, name: store.getters.orgName }]
    this.fetchData()
    this.fetchRoleData()
  },
  methods: {
    async fetchData() {
      this.listLoading = true
      await getAdminList({}).then(response => {
        console.log(response)
        this.userList = response.data
        this.listLoading = false
      })
    },
    async fetchRoleData() {
      this.listLoading = true
      await getRoleList().then(response => {
        this.roleList = response.data
        this.listLoading = false
      })
    },
    showRoleName(roleId) {
      const role = this.roleList.filter(item => item.id === roleId)
      if (role[0]) {
        return role[0].roleName
      }
    },
    handleCreate() {
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.tempData = {}
      this.tempData.sellerId = store.getters.orgId
      this.tempData.status = 1
      this.tempData.birthDate = '1990-01-01'
    },
    handleEdit(row) {
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      this.tempData = row
    },
    handleAcc(row) {
      this.accData.userId = row.id
      this.accData.name = row.name
      getAdmin(row.id).then(response => {
        this.accFormVisible = true
        if (response.data) {
          this.dialogStatus = 'update'
          const data = response.data
          this.accData.userName = data.userName
          this.accData.id = data.id
          this.accData.status = data.status
          this.accData.createTime = data.createTime
        } else {
          this.dialogStatus = 'create'
          this.accData.userName = ''
          this.accData.status = 1
          this.$notify({
            title: '提示',
            message: '该用户还没有帐号，请为该用户创建帐号。',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    createData() {
      addUserInfo(this.tempData).then(response => {
        this.$notify({
          title: `操作成功`,
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.fetchData()
      })
      this.dialogFormVisible = false
    },
    confirmEdit(row) {
      console.log(row)
      editUserInfo(row).then(response => {
        this.$notify({
          title: 'Success',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
      row.origName = row.privName
      row.origUrl = row.url
      row.edit = !row.edit
      this.dialogFormVisible = false
    },
    createAccData() {
      if (!this.accData.userName) {
        this.$notify({
          title: '提示',
          message: '请输入用户帐号名称',
          type: 'warning',
          duration: 2000
        })
        return
      }
      addAdmin(this.accData).then(response => {
        this.$notify({
          title: `操作成功`,
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
      this.dialogFormVisible = false
    },
    confirmAccEdit(row) {
      console.log(row)
      editAdmin(row).then(response => {
        this.$notify({
          title: 'Success',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
      this.dialogFormVisible = false
    },
    confirmStatus(row) {
      const status = 1 - row.status
      console.log(row)
      editUserStatus(row.id, status).then(response => {
        row.status = status
        this.$notify({
          title: response.message,
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped="scoped">
</style>
